package com.gopay.scheduler.job;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.common.order.dao.CommonQueryDAO;
import com.gopay.common.util.DateUtils;
import com.gopay.scheduler.GopayBaseJob;
import com.gopay.sms.client.GopaySMSHttpClient;
import com.gopay.sms.common.constants.SMSAppId;
import com.gopay.sms.common.domain.RequestVO;
import com.gopay.sms.common.domain.ResponseVO;

/**
 * 查询未入账的成功订单
 * 
 * @SuccessOrderWithOutInAcctWarningJob.java
 * @author fanghw
 * @2016年12月16日 下午4:34:14  www.gopay.com.cn Inc.All rights reserved.
 */
public class SuccessOrderWithOutInAcctWarningJob extends GopayBaseJob {
	private Logger logger = LoggerFactory
			.getLogger(SuccessOrderWithOutInAcctWarningJob.class);
	private static final String SWITCH_ON = "on";
	@Resource(name = "smsConfig")
	private Map<String, String> smsConfig;

	
	@Resource(name = "commonQueryDAO")
    private CommonQueryDAO commonQueryDAO;

	@Override
	public void doJobInternal() {
		//以前查询性能太慢，故重新实现  add by fanghw 20161216  ------------start	    
	    Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DAY_OF_MONTH, -30);
        //日期T-30
        String startDate=DateUtils.format(calendar.getTime(), "yyyyMMdd");
        logger.info("查询未入账的成功订单数量startDate="+startDate);
        
        //查询未入账的成功订单数量
	    int count=queryUndoAcctSuccOrderCount(startDate);	    
	    logger.info("查询未入账的成功订单数量count="+count);
	    
	    //发告警短信
	    if(count>0){
	        sendSms(count);
	    }
	   
	}
	
	/**
	 * 查询未入账的成功订单数量
	 * add by fanghw 20161216
	 * @param startDate
	 * @return
	 */
	private int queryUndoAcctSuccOrderCount(String startDate){
	    int count =0;
	    StringBuilder sb = new StringBuilder();

	    sb.append(" select t.gopay_order_id,t.txn_sta_cd from CPS_GEN_MAIN_ORDER t ");
	    sb.append(" left join BIS_BANK_MAIN_ORDER b on b.gopay_order_id=t.gopay_order_id ");
	    sb.append(" left join ACPS_ACCT_TRANS_DTL a on a.gopay_order_id=t.gopay_order_id ");
	    sb.append(" where 1=1 ");
	    sb.append(" and t.tran_finish_time<=sysdate-1*2/24 ");
	    sb.append(" and a.gopay_order_id is null ");	    
	    sb.append(" and b.order_status in ('00','02','03','04') ");
	    sb.append(" and t.txn_sta_cd in (20000,30102) ");	    
	    sb.append(" and t.gopay_int_txn_cd not in ('01734','01735','01738') "); //方红文要求排除01734交易,钱立东追加01735汇款拆分总支付订单
	    sb.append(" and t.gopay_txn_tm>=to_date(:startDate,'yyyymmdd') ");
	    

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("startDate", startDate);

        List<Object[]> rsList = commonQueryDAO.findBySql(sb.toString(), map);
        if (rsList != null && rsList.size() > 0) {
            for (Object[] arr : rsList) {
                count++;
                logger.info("未入账订单号"+arr[0]);                
            }
        }
	    
        return count;
	}

	private void sendSms(int num) {

		try {
			if (SWITCH_ON.equals(smsConfig.get("switch"))) {
				// 自定义短信内容，不提供验证码校验功能
				RequestVO req = new RequestVO();
				req.setAppId(SMSAppId._90000.value);
				req.setMobile(smsConfig.get("mobile"));// 电话号码(多个以逗号分隔)
				req.setContent("国付宝未入账的成功订单有" + num + "个，请及时处理。");
				ResponseVO resp = GopaySMSHttpClient.getInstance()
						.createVerificationCode(req);

				if (resp != null) {
					if ("100".equals(resp.getStatusCode())) {
						logger.error("检查未入账的成功订单预警短信发送成功");
					} else {
						logger.error("检查未入账的成功订单预警短信发送失败，原因：" + resp.getMessage());
					}
				}
			} else {
				logger.error("cron 预警短信发送已关闭.");

			}
		} catch (Exception e) {
			logger.error("senSMS error: ", e);
		}

	}

	public Map<String, String> getSmsConfig() {
		return smsConfig;
	}

	public void setSmsConfig(Map<String, String> smsConfig) {
		this.smsConfig = smsConfig;
	}

	
}
